import { ref } from 'vue'
import type { LocationCode } from '@/common/types/request'
import { useUserStore } from '@/common/store'
import { addressToCodeService, codeToAddressService } from '@/common/service/tx-map'

const key = ref(import.meta.env.HOPE_TX_MAP_KEY)
const referer = ref(import.meta.env.HOPE_TX_MAP_APP_NAME)

/**
 * 打开腾讯路线规划地图
 * @param targetAddress
 * @author lian
 */
export const openTXMapRoutePlan = async (targetAddress: string, locationCoder?: LocationCode) => {
  console.log('targetAddress:', targetAddress)
  console.log('locationCoder:', locationCoder)

  const { hope_user_info } = useUserStore()
  /** 目标地址 */
  const targetLocation = ref({
    latitude: 0,
    longitude: 0,
    address: targetAddress,
  })

  /** 用户地址 */
  const userLocation = ref({
    latitude: 0,
    longitude: 0,
    address: hope_user_info?.address,
  })

  // 如果用户传递了经纬度则使用用户传递的
  // if (locationCoder) {
  //   userLocation.value.longitude = locationCoder.longitude
  //   userLocation.value.latitude = locationCoder.latitude
  // }
  // else {
  //   if (!userLocation.value.address)
  //     return showSimpleToast('请先填写用户地址')

  //   // 否则则获取
  //   /**
  //    * 用户经纬度
  //    */
  //   const userCoder = await addressToCodeService(userLocation.value.address!) as any
  //   userLocation.value.longitude = userCoder.lng
  //   userLocation.value.latitude = userCoder.lat
  // }

  // TODO:将经纬度转换为地址
  // codeToAddressService(targetLocation.value)

  /**
   * 目标经纬度
   */
  const targetCoder = await addressToCodeService(targetLocation.value.address) as any
  targetLocation.value.longitude = targetCoder.lng
  targetLocation.value.latitude = targetCoder.lat

  /**
   * 起始地址
   */
  const startPoint = JSON.stringify({
    name: userLocation.value.address ? userLocation.value.address : '',
    scale: 18,
    latitude: userLocation.value.latitude,
    longitude: userLocation.value.longitude,
  })

  /**
   * 终点地址
   */
  const endPoint = JSON.stringify({
    name: targetLocation.value.address,
    scale: 18,
    latitude: targetLocation.value.latitude,
    longitude: targetLocation.value.longitude,
  })

  goToPage(`plugin://routePlan/index?key=${key.value}&referer=${referer.value}&endPoint=${endPoint}`)
}

/**
 * 打开腾讯地图选点
 *
 * @author lian
 */
export const openTXMapChooseLocation = () => {
  let location

  uni.getLocation({
    type: 'wgs84',
    success(result) {
      const { latitude, longitude } = result

      location = JSON.stringify({
        latitude,
        longitude,
      })
      goToPage(`plugin://chooseLocation/index?key=${key.value}&referer=${referer.value}&location=${location}`)
    },
  })
}
